package com.anket.person;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.AjaxBehaviorEvent;
import javax.servlet.http.HttpSession;

import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.primefaces.model.StreamedContent;
import org.primefaces.model.chart.PieChartModel;

import com.anket.DynamicImageController;
import com.anket.address.bo.AddressBo;
import com.anket.address.model.Address;
import com.anket.city.model.City;
import com.anket.country.model.Country;
import com.anket.district.model.District;
import com.anket.option.model.Option;
import com.anket.person.bo.PersonBo;
import com.anket.person.model.Person;
import com.anket.poll.model.Poll;

@ManagedBean(name = "personBean")
@SessionScoped
public class PersonBean implements Serializable {

	PersonBo personBo;
	AddressBo addressBo;

	public Person tempPerson;
	public Address tempAddress;
	
	private Country tempCountry;

	public Country getTempCountry() {
		return tempCountry;
	}

	public void setTempCountry(Country tempCountry) {
		this.tempCountry = tempCountry;
	}

	public Poll tempPoll;
	public Option tempOption;

	public String email = "";
	public String password = "";

	public String pollTitle = "";

	public boolean login = false;
	public boolean logout = true;

	private int sizeOfOption;

	private List<Car> allCars;

	private String test;

	private String size;

	private List<Option> optionList;

	private Date date1;

	private Poll selectedPoll;

	private PieChartModel model;

	public PieChartModel getModel() {

		model = new PieChartModel();
		if (selectedPoll != null)
			for (Option option : selectedPoll.getAllOptions()) {
				model.set(option.content, option.click);
			}

		return model;
	}
	
	public StreamedContent printChart(){
		
		DefaultPieDataset dataset = new DefaultPieDataset();
		if (selectedPoll != null)
			for (Option option : selectedPoll.getAllOptions()) {
				dataset.setValue(option.content.toString(), new Double(45.0));
			}
		
		dataset.setValue("Istanbul", new Double(45.0));  
		return (new DynamicImageController()).print((PieDataset)dataset);
		
	}
	
	public String getGoogleChartData(){
		
		String str="";
		
		if (selectedPoll != null){
			int val=0;
			val=selectedPoll.getAllOptions().size();
			
			
			int i=0;
			
			str+="data.addRows([";
			
			for (Option option : selectedPoll.getAllOptions()) {
				str+="['"+option.getContent()+"',"+(i+1)*10+"]";
				if(i!=val-1)str+=",";
//				str+="data.setValue("+i+",0,'"+option.getContent()+"');";
//				str+="data.setValue("+i+",1,"+i*10+");";
				i++;
			}
			str+="]);";
			
		}
			
		
		return str;
	}

	public Poll getSelectedPoll() {
		return selectedPoll;
	}

	public void setSelectedPoll(Poll selectedPoll) {
		this.selectedPoll = selectedPoll;
	}

	public Date getDate1() {
		return date1;
	}

	public void setDate1(Date date1) {
		this.date1 = date1;
	}

	public String getSize() {
		return size;
	}

	public void setSize(String size) {
		this.size = size;

	}

	public String getTest() {
		return test;
	}

	public void setTest(String test) {
		this.test = test;
	}

	public List<Car> getAllCars() {
		return allCars;
	}

	public void setAllCars(List<Car> allCars) {
		this.allCars = allCars;
	}

	public Option getTempOption() {
		return tempOption;
	}

	public void setTempOption(Option tempOption) {
		this.tempOption = tempOption;
	}

	public String getPollTitle() {
		return pollTitle;
	}

	public void setPollTitle(String pollTitle) {
		this.pollTitle = pollTitle;
	}

	public Poll getTempPoll() {
		return tempPoll;
	}

	public void setTempPoll(Poll tempPoll) {
		this.tempPoll = tempPoll;
	}

	public int getSizeOfOption() {
		return sizeOfOption;
	}

	public void setSizeOfOption(int sizeOfOption) {
		this.sizeOfOption = sizeOfOption;
	}

	public void handleOptionChange(AjaxBehaviorEvent event) {
		// gridComponent.setColumns(sizeOfOption);
		try {
			addFunction(sizeOfOption);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void addFunction(int number) throws IOException {

		FacesContext context = FacesContext.getCurrentInstance();

		optionList.clear();
		for (int i = 0; i < number; i++) {
			tempOption = new Option();
			optionList.add(tempOption);
		}

	}

	public List<Option> getOptionList() {
		return optionList;
	}

	public void setOptionList(List<Option> optionList) {
		this.optionList = optionList;
	}

	public boolean isLogin() {
		return login;
	}

	public void setLogin(boolean login) {
		this.login = login;
	}

	public boolean isLogout() {
		return logout;
	}

	public void setLogout(boolean logout) {
		this.logout = logout;
	}

	public List<Country> getAllCountries() {
		return addressBo.getAllCountries();
	}

	public List<City> getAllCities() {
		return addressBo.getAllCities((int) tempAddress.getCountry().getCountryId());
	}

	public List<District> getAllDistricts() {
		return addressBo.getAllDistricts((int) tempAddress.getCity().getCityId());
	}

	public AddressBo getAddressBo() {
		return addressBo;
	}

	public void setAddressBo(AddressBo addressBo) {
		this.addressBo = addressBo;
	}

	public Address getTempAddress() {
		return tempAddress;
	}

	public void setTempAddress(Address tempAddress) {
		this.tempAddress = tempAddress;
	}

	public PersonBean() {
		tempPerson = new Person();
		tempAddress = new Address();
		tempPoll = new Poll();
		tempOption = new Option();

		allCars = new ArrayList<Car>();
		optionList = new ArrayList<Option>();

		for (int i = 0; i < 5; i++) {

			Car car = new Car("mercedes", "" + i + 1);

			allCars.add(car);

		}

	}

	public PersonBo getPersonBo() {
		return personBo;
	}

	public void setPersonBo(PersonBo personBo) {
		this.personBo = personBo;
	}

	public Person getTempPerson() {
		return tempPerson;
	}

	public void setTempPerson(Person tempPerson) {
		this.tempPerson = tempPerson;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String addPerson() {
	
		tempPerson.setAddress(personBo.prepareAddress(tempAddress));
		tempPerson.setIsAdmin(0);
		tempPerson.setStatus(0);
		personBo.addPerson(tempPerson);

		//clearForm();

		return "";
	}

	public String addPoll() {

		tempPoll = new Poll();

		HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
		String id = session.getAttribute("id").toString();

		Person person = personBo.getPersonById(Integer.parseInt(id));
		tempPoll.setPerson(person);
		tempPoll.setTitle(pollTitle);

		// tempOption = new Option();

		Iterator ite = optionList.iterator();
		while (ite.hasNext()) {
			tempOption = (Option) ite.next();
			tempOption.setPoll(tempPoll);
			tempOption.setClick(-1);
			personBo.addOption(tempOption);
		}
		return "";
	}

	public Person isLoginTrue() {
		return personBo.isloginTrue(email, password);
	}

	public String doLogin() {
		System.out.println("login");

		Person person = isLoginTrue();

		if (person != null) {
			HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
			session.setAttribute("isLoggedIn", "yes");
			session.setAttribute("id", person.getPersonId());

			login = true;
			logout = false;
		}

		System.out.println("----" + isLoginTrue());
		return person != null ? "homepage" : "";
	}

	public String doLogout() {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);

		session.invalidate();
		login = false;
		logout = true;
		return "login";
	}

	public void clearForm() {
		tempPerson.setName("");
		tempPerson.setLastname("");
		tempPerson.setPassword("");
		tempPerson.setEmail("");
		tempAddress.setShortAddress("");
		tempAddress.getCountry().setCountryId(0);
		tempAddress.setShortAddress("");
		tempAddress.getDistrict().setDistrictId(0);
		tempAddress.getCity().setCityId(0);

	}

	public void fonk1() {

		Object sessionName = "name";
		Object sessionValue = "value";

		FacesContext facesContext = FacesContext.getCurrentInstance();
		HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);
		Enumeration e = session.getAttributeNames();

		while (e.hasMoreElements()) {
			String attr = (String) e.nextElement();
			System.err.println("      attr  = " + attr);
			Object value = session.getValue(attr);
			System.err.println("      value = " + value);
		}

		// session.setAttribute("name", new String("mustafa"));

		System.out.println("\n--end of fonk1--\n");

	}

	public void fonk2() {

		FacesContext facesContext = FacesContext.getCurrentInstance();
		HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);
		Enumeration e = session.getAttributeNames();

		while (e.hasMoreElements()) {
			String attr = (String) e.nextElement();
			System.err.println("      attr  = " + attr);
			Object value = session.getValue(attr);
			System.err.println("      value = " + value);
		}

		System.out.println("\n--end of fonk2--\n");

	}

	public void fonk3() {

		FacesContext facesContext = FacesContext.getCurrentInstance();
		HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);
		Enumeration e = session.getAttributeNames();

		session.invalidate();

		System.out.println("\n--end of fonk3--\n");

	}

	public void fonk4() {
		FacesContext fc = FacesContext.getCurrentInstance();
		System.out.println("view id=" + fc.getViewRoot().getViewId());
	}

	public boolean loggedIn() {
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
		String isLog = (String) session.getAttribute("isLoggedIn");
		System.out.println("isLoggedIn: " + isLog);
		return (isLog != null && isLog.equals("yes"));
	}

	public List<Poll> getAllPolls() {

		HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
		String id = session.getAttribute("id").toString();

		Person person = personBo.getPersonById(Integer.parseInt(id));
		return person.getAllPolls();

	}

}
